/**
 * 统一API客户端
 * 兼容小程序和H5环境
 */
import Taro from '@tarojs/taro';
import { getApiBaseUrl } from '../utils/env';
import { BaseResponse } from '../types/response';
import { removeToken, getToken } from '../contexts/store';
import DefaultImage from '../assets/default/default-image.jpg';
import { generateRandomString, IMAGE_BASE_URL } from '../utils/common';


// API基础URL
const API_BASE_URL = getApiBaseUrl();


/**
 * 页面跳转，兼容不同环境
 */
const redirectToLogin = () => {
    Taro.redirectTo({ url: '/pages/login/index' });
};

/**
 * API请求配置接口
 */
interface ApiRequestConfig {
    url: string;
    method: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: any;
    params?: any;
    headers?: Record<string, string>;
    timeout?: number;
}

/**
 * 生成请求头信息
 * @returns 请求头对象
 */
const generateHeaders = (): Record<string, string> => {
    const token = getToken();
    const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
        'X-Auth-token': token,
        'X-Auth-version': '1.0',
        'X-Auth-signature': generateRandomString(16),
        'X-Auth-timestamp': Date.now().toString()
    };
    return headers;
};

/**
 * API请求方法
 * @param config 请求配置
 * @returns Promise<BaseResponse<T>>
 */
export const request = async <T = any>(config: ApiRequestConfig): Promise<BaseResponse<T>> => {
    try {
        // 构建完整的URL
        let fullUrl = config.url.startsWith('http') ? config.url : `${API_BASE_URL}${config.url}`;
        // 构建请求头
        const headers = { ...generateHeaders(), ...config.headers };
        
        // 如果是GET请求，将params转换为查询参数
        if (config.method === 'GET' && config.params) {
            const queryParams = new URLSearchParams(config.params).toString();
            fullUrl = `${fullUrl}${fullUrl.includes('?') ? '&' : '?'}${queryParams}`;
        }
        
        // 统一使用Taro.request，兼容小程序和H5环境
        const requestOptions: Taro.request.Option = {
            url: fullUrl,
            method: config.method,
            header: headers,
            data: config.data,
            timeout: config.timeout || 120000
        };
        
        const response = await Taro.request(requestOptions);
        if (response.statusCode === 401) {
            removeToken();
            redirectToLogin();
            console.log('未授权，请重新登录:', requestOptions);
            throw new Error('未授权，请重新登录');
        }
        return response.data as BaseResponse<T>;
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
};

/**
 * 简化的GET请求方法
 * @param url 请求URL
 * @param params 查询参数
 * @returns Promise<BaseResponse<T>>
 */
export const get = async <T = any>(url: string, params?: any): Promise<BaseResponse<T>> => {
    return request<T>({
        url,
        method: 'GET',
        params
    });
};

/**
 * 简化的POST请求方法
 * @param url 请求URL
 * @param data 请求数据
 * @returns Promise<BaseResponse<T>>
 */
export const post = async <T = any>(url: string, data?: any): Promise<BaseResponse<T>> => {
    return request<T>({
        url,
        method: 'POST',
        data
    });
};

/**
 * 简化的PUT请求方法
 * @param url 请求URL
 * @param data 请求数据
 * @returns Promise<BaseResponse<T>>
 */
export const put = async <T = any>(url: string, data?: any): Promise<BaseResponse<T>> => {
    return request<T>({
        url,
        method: 'PUT',
        data
    });
};

/**
 * 简化的DELETE请求方法
 * @param url 请求URL
 * @param data 请求数据
 * @returns Promise<BaseResponse<T>>
 */
export const del = async <T = any>(url: string, data?: any): Promise<BaseResponse<T>> => {
    return request<T>({
        url,
        method: 'DELETE',
        data
    });
};

/**
 * 获取静态文件的临时访问路径
 * @param key 静态文件键名
 * @returns Promise<string>
 */
export const getAssetsFileUrl = async(key: string): Promise<string> => {
    try {
        const response = await request({
            url: '/api/common/v1/oss-url',
            method: 'GET',
            params: { key }
        });
        if(response.code == 200) {
          return response.data;
        }else{
            return DefaultImage
        }
    } catch (error) {
        return DefaultImage
    }
};


export const assetsFileUrl = async(key: string):  Promise<string> => {
    if (!key) {
        return DefaultImage;
    }
    else if (key.startsWith('http') || key.startsWith("data:image")) {
        return key;
    }
    else if (key.startsWith('public')) {
        return key.startsWith("/") ? `${IMAGE_BASE_URL}${key}` : `${IMAGE_BASE_URL}/${key}`;
    }
    return await getAssetsFileUrl(key);
};


// 导出API客户端对象
export default {
    request,
    get,
    post,
    put,
    delete: del,
    assetsFileUrl
};


